package com.guodefu.demo.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.CacheOperationInvocationContext;
import org.springframework.cache.interceptor.SimpleCacheResolver;
import org.springframework.cache.transaction.TransactionAwareCacheDecorator;
import org.springframework.data.redis.cache.RedisCache;

import java.time.Duration;
import java.util.Collection;
import java.util.Set;

//@Component
public class CustomCacheResolver extends SimpleCacheResolver {

    private final CacheManager cacheManager;

    public CustomCacheResolver(CacheManager cacheManager) {
        super(cacheManager);
        this.cacheManager = cacheManager;
    }

    @Override
    protected Collection<String> getCacheNames(CacheOperationInvocationContext<?> context) {
        // 获取自定义注解
        CacheExpire cacheExpire = context.getMethod().getAnnotation(CacheExpire.class);
        if (cacheExpire != null) {
            // 获取缓存名
            Set<String> cacheNames = context.getOperation().getCacheNames();
            for (String cacheName : cacheNames) {
                // 获取缓存对象
                TransactionAwareCacheDecorator cacheDecorator = (TransactionAwareCacheDecorator)cacheManager.getCache(cacheName);
                RedisCache cache = (RedisCache) cacheDecorator.getTargetCache();
                // 重新配置过期时间
                assert cache != null;
                cache.getCacheConfiguration().entryTtl(Duration.ofSeconds(cacheExpire.expire()));
            }
            return cacheNames;
        }
        return super.getCacheNames(context);
    }
}
